<script setup lang="ts">
import F_footer from "@/components/web/f_footer.vue";
import {IconImage} from "@arco-design/web-vue/es/icon";
import {onMounted, reactive, ref} from "vue";
import {aiRoleListApi, type aiRoleType} from "@/api/ai_role_api";
import type {listResponse} from "@/api";
import {Message} from "@arco-design/web-vue";
import F_text from "@/components/common/f_text.vue";
import F_banner from "@/components/web/f_banner.vue";
import type {chatCreateType} from "@/api/chat_api";
import {sessionCreateApi} from "@/api/session_list_api";
import router from "@/router";
import {userStorei} from "@/stores/user_store";
import {imageUploadApi} from "@/api/image_api";
import {base64UrlToFile} from "@/utils/file";
import {getSessionIDByRoleID} from "@/service/get_session_id_by_role_id";
import {showLogin} from "@/components/web/f_login";

const store = userStorei()

const iptRef = ref()
onMounted(() => {
  // 刚进页面，自动选中输入框
  iptRef.value.focus()
})

const data = reactive<listResponse<aiRoleType>>({
  list: [],
  count: 0,
})

async function getAiRoleList() {
  const res = await aiRoleListApi({type: 2})
  if (res.code) {
    Message.error(res.msg)
    return
  }
  Object.assign(data, res.data)
}

getAiRoleList()

const body = reactive<chatCreateType>({
  sessionID: 0,
  content: "",
  imageList: []
})

async function newSession() {
  if (body.content.trim() === "") {
    return
  }
  if (!store.isLogin){
    Message.warning("需要登陆")
    showLogin()
    return
  }
  const res = await sessionCreateApi()
  if (res.code) {
    Message.error(res.msg)
    return
  }
  store.chat.content = body.content
  store.chat.imageList = body.imageList as string[]
  router.push({name: "chat", params: {id: res.data}})
}

const imgIptRef = ref()

function imgClick() {
  if (!store.isLogin){
    Message.warning("需要登陆")
    showLogin()
    return
  }

  imgIptRef.value?.click()
}

async function imageChange(e: Event) {
  const target = e.target as HTMLInputElement
  if (target.files && target.files.length) {
    const file = target.files[0]
    const res = await imageUploadApi(file)
    if (res.code) {
      Message.error(res.msg)
      return
    }
    Message.success(res.msg)
    body.imageList = [res.data]
  }
}

function paste(event: ClipboardEvent) {
  // 取消默认事件
  // event.preventDefault();
  const items = (event.clipboardData as DataTransfer).items;
  for (const index in items) {
    const item = items[index];
    if (item.kind === 'file') {
      const blob = item.getAsFile();
      const reader = new FileReader();
      reader.onload = async (event: ProgressEvent<FileReader>) => {
        // 这里是在前端显示图片，可以自由操作是上传后端还是进行文件操作
        const file = base64UrlToFile((event.target as FileReader).result as string, "img.png")
        // console.log(file)
        const res = await imageUploadApi(file)
        if (res.code) {
          Message.error(res.msg)
          return
        }
        Message.success(res.msg)
        body.imageList = [res.data]
        // console.log(event)
        return
      };
      reader.readAsDataURL(blob as File);
    }
  }
}


</script>

<template>
  <div class="web_home_view">
    <f_banner></f_banner>
    <div class="ipt">
      <a-input @keydown.enter="newSession" @paste="paste" v-model="body.content" ref="iptRef"
               placeholder="输入你的问题"></a-input>
      <div class="icon_bg" @click="imgClick">
        <IconImage></IconImage>
        <input style="display: none" ref="imgIptRef" @change="imageChange" type="file" accept="image/*">
        <div class="up_img_show" v-if="body.imageList?.length">
          <a-image :height="60" v-for="src in body.imageList" :src="src"></a-image>
        </div>
      </div>
      <a-button type="primary" @click="newSession" :disabled="body.content.trim() === ''">搜索</a-button>
    </div>
    <div class="hot_role">
      <div class="label">热门角色</div>
      <div class="role_list" v-if="data.list.length">
        <div class="item" v-for="item in data.list">
          <div class="avatar">
            <a-avatar :image-url="item.avatar"></a-avatar>
          </div>
          <div class="info">
            <div class="title">
              <f_text> {{ item.title }}</f_text>
            </div>
            <div class="user">
              <f_text> @{{ item.roleUserNickname }}</f_text>
            </div>
          </div>
          <div class="abs">
            <f_text :rows="2">{{ item.abstract }}</f_text>
          </div>
          <div class="icon_send" @click="getSessionIDByRoleID(item.id)">
            <i class="iconfont icon-24gl-paperPlane"></i>
          </div>
        </div>
      </div>
      <div class="role_list" v-else>
        <a-empty></a-empty>
      </div>

    </div>
    <F_footer class="footer"></F_footer>
  </div>
</template>

<style lang="less">
.web_home_view {


  .ipt {
    display: flex;
    align-items: center;
    margin: 20px 0;

    .icon_bg {
      border-radius: 5px;
      border: @f_border;
      display: flex;
      justify-content: center;
      height: 32px;
      padding: 0 15px;
      align-items: center;
      margin: 0 10px;
      cursor: pointer;
      position: relative;

      .up_img_show {
        position: absolute;
        bottom: -75px;
        background-color: var(--color-fill-2);
        border-radius: 5px;
        padding: 5px;
        z-index: 2;
      }

      svg {
        font-size: 20px;
        color: var(--color-text-2);
      }
    }
  }

  .hot_role {
    margin-top: 40px;

    .label {
      color: var(--color-text-2);
    }

    .item {
      margin-top: 15px;
      width: 100%;
      border-radius: 5px;
      border: @f_border;
      display: flex;
      padding: 10px;
      height: 80px;

      .avatar {
        width: 50px;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .info {
        width: 120px;
        display: flex;
        flex-direction: column;
        justify-content: center;

        .title {
          font-weight: 600;
        }

        .user {
          color: var(--color-text-2);
          margin-top: 2px;
        }
      }

      .abs {
        width: calc(100% - 250px);
        display: flex;
        align-items: center;

        .arco-typography {
          color: var(--color-text-2);
        }
      }

      .icon_send {
        width: 80px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;

        svg {
          color: var(--color-text-2);
          font-size: 20px;
          cursor: pointer;
        }
      }
    }
  }

  .footer {
    position: fixed;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
  }
}
</style>